<style lang="less">
  @import '../styles/common.less';
  @import '../tables/components/table.less';
</style>

<template>
  <div>
    <Row :gutter="10">
      <Card>
        <div class="table-head">
          <div class="left">
            <Select v-model="typeSelectid" :transfer="true" @on-change="onChangeTypeSelect">
              <Option v-for="item in typeSelect" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </div>
          <div class="left">
            <DatePicker
                type="daterange"
                placement="bottom-start"
                placeholder="时间段"
                v-model="searchDatePicker"
                style="width: 100%;"></DatePicker>
          </div>
          <div class="left-btn">
            <Button type="primary" @click="searchFun()">搜索</Button>
          </div>
          <Button type="primary" class="Button" @click="reportUserFun()">设置默认知会人</Button>
          <Button type="primary" class="Button" @click="ExportData()">导出数据</Button>
          <Button type="primary" class="Button" @click="remove()">删除</Button>
          <Button type="primary" class="Button" @click="add()">添加</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data" @on-row-click="onRowData" @on-sort-change="onSortChange"
                 @on-selection-change="selectionChange"></Table>
        </Row>
        <div style="margin: 10px;overflow: hidden;height: 36px;">
          <div style="float: right;">
            <Page :total="total" :current="page" @on-change="changePage" show-elevator></Page>
          </div>
        </div>
      </Card>
      <!--详情-->
      <Drawer :closable="false" :width="DrawerWidth" v-model="showCurrentTableData" class="Drawer-body">
        <p class="Drawer_pStyle">查看详情</p>
        <div class="body">
          <Form label-position="top">
            <FormItem label="标题">
              <div class="dataDetail-div" v-text="dataDetail.title"></div>
            </FormItem>
            <FormItem label="任务描述">
              <div class="dataDetail-div" v-text="dataDetail.content"></div>
            </FormItem>
            <FormItem label="创建人" v-if="dataDetail.creator">
              <div class="dataDetail-div" v-text="dataDetail.creator.name"></div>
            </FormItem>
            <FormItem label="创建时间">
              <div class="dataDetail-div" v-text="dataDetail.create_time"></div>
            </FormItem>
            <FormItem label="截止时间">
              <div class="dataDetail-div" v-text="dataDetail.deadline"></div>
            </FormItem>
            <FormItem label="优先级">
              <div class="dataDetail-div" v-text="dataDetail.priority"></div>
            </FormItem>
            <FormItem label="状态">
              <div class="dataDetail-div" v-text="dataDetail.status"></div>
            </FormItem>
            <FormItem label="任务负责人" v-if="dataDetail.charge">
              <div class="dataDetail-div user-avatar-div">
                <user-avatar
                    :user_id="dataDetail.charge.id"
                    :user_name="dataDetail.charge.name"
                    :user_img="dataDetail.charge.avatar.thumb"
                    :fun="searchUserInfo"
                >
                </user-avatar>
              </div>
            </FormItem>
            <FormItem label="任务协作人" v-if="dataDetail.cowork && dataDetail.cowork.length > 0">
              <div class="dataDetail-div user-avatar-div">
                <user-avatar
                    v-for="(el,index) in dataDetail.cowork"
                    :key="'cowork_user' + index"
                    :user_id="el.id"
                    :user_name="el.name"
                    :user_img="el.avatar.thumb"
                    :fun="searchUserInfo"
                >
                </user-avatar>
              </div>
            </FormItem>
            <FormItem label="任务知会人" v-if="dataDetail.noticer && dataDetail.noticer.length > 0">
              <div class="dataDetail-div user-avatar-div">
                <user-avatar
                    v-for="(el,index) in dataDetail.noticer"
                    :key="'noticer_user' + index"
                    :user_id="el.id"
                    :user_name="el.name"
                    :user_img="el.avatar.thumb"
                    :fun="searchUserInfo"
                >
                </user-avatar>
              </div>
            </FormItem>
            <FormItem label="子任务">
              <div class="table-head" style="margin-bottom: 5px;">
                <Button type="primary" class="" @click="addChildren('addchildren')">添加子任务</Button>
              </div>
              <div class="dataDetail-div padding-0" v-if="dataDetail.children && dataDetail.children.length > 0">
                <Table stripe border :columns="children_columns" :data="dataDetail.children"
                       @on-row-click="onRowData"
                       v-if="dataDetail.children && dataDetail.children.length > 0"></Table>
              </div>
            </FormItem>
          </Form>
        </div>
        <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">
          <Button type="text" @click="hideDetailModal">取消</Button>
          <Button type="primary" :loading="saveLoading" v-if="status == 'not-begun' || status == 'paused'"
                  @click="task_start()">开始
          </Button>
          <Button type="primary" :loading="saveLoading" v-if="status == 'started'"
                  @click="task_pause()">暂停
          </Button>
          <Button type="primary" :loading="saveLoading"
                  v-if="status == 'finished' || status == 'ahead-finished' || status == 'overtime-finished' || status == 'archived'"
                  @click="task_reopen()">重开
          </Button>
          <Button type="primary" :loading="saveLoading"
                  v-if="status == 'not-begun' || status == 'started' || status == 'delayed'  || status == 'paused'"
                  @click="task_over()">完成
          </Button>
          <Button type="primary" :loading="saveLoading"
                  v-if="status == 'finished' || status == 'ahead-finished' || status == 'overtime-finished'"
                  @click="task_archive()">归档
          </Button>
        </div>
      </Drawer>
      <!--编辑-->
      <Drawer :closable="false" :width="DrawerWidth" v-model="addCurrentTableData" class="Drawer-body">
        <p class="Drawer_pStyle">编辑</p>
        <div class="body">
          <Form label-position="top">
            <FormItem label="标题">
              <Input v-model="addData.title" placeholder="标题"></Input>
            </FormItem>
            <FormItem label="任务描述">
              <Input v-model="addData.content" type="textarea" class="textarea_resize"
                     :autosize="{minRows: 3}" placeholder="任务描述"></Input>
            </FormItem>
            <FormItem label="优先级">
              <Select v-model="addData.priority" :transfer="true" style="width:100%;">
                <Option v-for="item in priorityArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
              </Select>
            </FormItem>
            <FormItem label="交付时间">
              <DatePicker type="datetime"
                          format="yyyy-MM-dd HH:mm:ss"
                          :confirm="true"
                          :transfer="true"
                          :editable="false"
                          placement="bottom-start"
                          placeholder="请选择交付时间"
                          v-model="addData.DatePickerValue"
                          style="width: 100%;"></DatePicker>
            </FormItem>
            <FormItem label="任务负责人">
              <div class="dataDetail-div">
                <Tree ref="charge_tree" :data="chargeTreeData" @on-select-change="onSelectChange"></Tree>
              </div>
            </FormItem>
            <FormItem label="任务协作人" v-show="children != 'addchildren' && children != 'children'">
              <div class="dataDetail-div">
                <Tree ref="cowork_tree" :data="TreeData" show-checkbox></Tree>
              </div>
            </FormItem>
            <FormItem label="知会人">
              <div class="dataDetail-div">
                <Tree ref="report_tree" :data="reportTreeData" show-checkbox multiple></Tree>
              </div>
            </FormItem>
          </Form>
        </div>
        <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">
          <Button type="text" @click="hideAddModal">取消</Button>
          <Button type="primary" :loading="saveLoading" @click="save()">确定</Button>
        </div>
      </Drawer>
      <!--默认知会人-->
      <Drawer :closable="false" :width="DrawerWidth" v-model="reportUser" class="Drawer-body">
        <p class="Drawer_pStyle">设置默认知会人</p>
        <div class="body">
          <Form label-position="top">
            <FormItem label="知会人">
              <div class="dataDetail-div">
                <Tree ref="report_user" :data="reportTreeData" show-checkbox multiple></Tree>
              </div>
            </FormItem>
          </Form>
        </div>
        <div class="footer" :style="{width: DrawerWidth - 32 + 'px'}">
          <Button type="text" @click="hidereportUser">取消</Button>
          <Button type="info" :loading="saveLoading" @click="savereportUser">保存</Button>
        </div>
      </Drawer>
    </Row>
    <!--人员详情-->
    <user-info
        :user_id="userInfo_id"
        @userInfoBackFun="userInfoBackFun"
    ></user-info>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';
  import Ckeditor from '../../libs/mod.ckeditor';
  import userAvatar from '../components/user-avatar.vue';
  import userInfo from '../components/user-info.vue';
  export default {
    components: {
      userAvatar,
      userInfo
    },
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        sort: '',
        order: '',
        id: '',
        pid: 0,
        typeSelectid: 'todo',
        typeSelect: [
          {
            id: 'todo',
            name: '未完成',
          },
          {
            id: 'done',
            name: '已完成',
          },
          {
            id: 'archive',
            name: '已归档',
          },
        ],
        searchConName: '',
        searchConTel: '',
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            key: 'title',
            title: '标题',
            align: 'center',
            sortable: 'custom',
          },
          {
            key: 'charge',
            title: '负责人',
            align: 'center',
            sortable: 'custom',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.charge.name)
              ]);
            }
          },
          {
            key: 'priority',
            title: '优先级',
            align: 'center',
            sortable: 'custom',
            render: (h, params) => {
              var priority = params.row.priority;
              switch (priority) {
                case "normal" :
                  priority = '普通';
                  break;
                case "important" :
                  priority = '重要';
                  break;
                case "fatal" :
                  priority = '紧急';
                  break;
                default:
                  break;
              }
              return h('div', [
                h('span', priority)
              ]);
            }
          },
          {
            key: 'status',
            title: '状态',
            align: 'center',
            sortable: 'custom',
            render: (h, params) => {
              var status = params.row.status;
              switch (status) {
                case "not-begun" :
                  status = '未开始';
                  break;
                case "started" :
                  status = '已开始';
                  break;
                case "paused" :
                  status = '已暂停';
                  break;
                case "delayed" :
                  status = '已延期';
                  break;
                case "finished" :
                  status = '已完成';
                  break;
                case "archived" :
                  status = '已归档';
                  break;
                case "ahead-finished" :
                  status = '提前完成了';
                  break;
                case "overtime-finished" :
                  status = '延期完成了';
                  break;
                default:
                  break;
              }
              return h('div', [
                h('span', status)
              ]);
            }
          },
          {
            key: 'deadline',
            title: '截止日期',
            align: 'center',
            sortable: 'custom',
          },
          {
            title: 'Action',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small',
                    //disabled: !this.permissions,
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: e => {
                      e.stopPropagation();
                      var data = params.row;
                      this.update(data, params.index);
                    }
                  }
                }, '修改')
              ]);
            }
          }
        ],
        data: [],
        children_columns: [
          {
            key: 'title',
            title: '标题',
          },
          {
            key: 'charge',
            title: '负责人',
            render: (h, params) => {
              return h('div', [
                h('span', params.row.charge.name)
              ]);
            }
          },
          {
            key: 'priority',
            title: '优先级',
            render: (h, params) => {
              var priority = params.row.priority;
              switch (priority) {
                case "normal" :
                  priority = '普通';
                  break;
                case "important" :
                  priority = '重要';
                  break;
                case "fatal" :
                  priority = '紧急';
                  break;
                default:
                  break;
              }
              return h('div', [
                h('span', priority)
              ]);
            }
          },
          {
            key: 'status',
            title: '状态',
            render: (h, params) => {
              var status = params.row.status;
              switch (status) {
                case "not-begun" :
                  status = '未开始';
                  break;
                case "started" :
                  status = '已开始';
                  break;
                case "paused" :
                  status = '已暂停';
                  break;
                case "delayed" :
                  status = '已延期';
                  break;
                case "finished" :
                  status = '已完成';
                  break;
                case "archived" :
                  status = '已归档';
                  break;
                case "ahead-finished" :
                  status = '提前完成了';
                  break;
                case "overtime-finished" :
                  status = '延期完成了';
                  break;
                default:
                  break;
              }
              return h('div', [
                h('span', status)
              ]);
            }
          },
          {
            key: 'deadline',
            title: '截止日期',
            width: 160,
          },
          {
            title: 'Action',
            key: 'action',
            width: 80,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small',
                    //disabled: !this.permissions,
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: e => {
                      e.stopPropagation();
                      var data = params.row;
                      this.update(data, params.index, 'children');
                    }
                  }
                }, '修改')
              ]);
            }
          }
        ],
        children_data: [],
        dataDetail: {},
        initTable: [],
        addCurrentTableData: false,
        saveLoading: false,
        ajaxType: 'add',
        addData: {
          title: '',
          content: '',
          DatePickerValue: '',//'2018-06-06 10:10:00'
          priority: '',
          chargeId: '',
        },
        selectionArr: [],
        priorityArr: [
          {
            id: 'normal',
            name: '普通',
          },
          {
            id: 'important',
            name: '重要',
          },
          {
            id: 'fatal',
            name: '紧急',
          }
        ],
        TreeData: [],
        chargeTreeData: [],
        checked_dep_arr: [],
        checked_users_arr: [],
        editor: null,
        task_type: '',
        task_type_id: '',
        children: '',//是否为子任务
        status: '',//任务状态
        comePageTime: 0,// 进入页面的时间戳
        permissions: false,
        DrawerWidth: Util.constant.DrawerWidth,// 抽屉的宽度
        WindowWidth: Util.constant.WindowWidth,// 窗口的宽度
        WindowHeight: Util.constant.WindowHeight,// 窗口的高度
        reportUser: false,
        reportTreeData: [],
        report_checked_users_arr: [],
        userInfoDrawer: false,
        userInfo_id: '',// 查看用户详情的用户id
        searchDatePicker: [],//搜索时间段
        from: '',
        to: '',
      };
    },
    beforeMount: function () {
      var _this = this;
      var comePageTime = _this.comePageTime;
      var timestamp = new Date().getTime();
      _this.comePageTime = timestamp;
    },
    beforeDestroy: function () {
      var _this = this;
      var comePageTime = _this.comePageTime;
      var timestamp = new Date().getTime();
      var type = Util.constant.statistical_type.task.id;
      var seconds = Math.ceil((parseInt(timestamp) - parseInt(comePageTime)) / 1000);
      Util.statistical(_this, type, seconds);//保存数据
    },
    created: function () {
      var _this = this;

      // 城市管理跳转过来的
      var city_data = sessionStorage.getItem('city_data');
      if (city_data && city_data != '') {
        var datas = Util.toJson(city_data);
        var city_id = datas.city_id;
        var title = datas.title;
        var content = datas.content;
        _this.task_type = 'city';
        _this.task_type_id = city_id;
        _this.addData.title = title;
        _this.addData.content = content;
        _this.other_add();

        sessionStorage.removeItem('city_data');
      }
      // 安全整治跳转过来的
      var regulate_data = sessionStorage.getItem('regulate_data');
      if (regulate_data && regulate_data != '') {
        var datas = Util.toJson(regulate_data);
        var pid = datas.pid;
        var title = datas.title;
        var content = datas.content;
        _this.task_type = 'regulate';
        _this.task_type_id = pid;
        _this.addData.title = title;
        _this.addData.content = content;
        _this.other_add();

        sessionStorage.removeItem('regulate_data');
      }
      // 微心愿跳转过来的
      var regulate_data = sessionStorage.getItem('wish_data');
      if (regulate_data && regulate_data != '') {
        var datas = Util.toJson(regulate_data);
        var pid = datas.pid;
        var title = datas.title;
        var content = datas.content;
        _this.task_type = 'wish';
        _this.task_type_id = pid;
        _this.addData.title = title;
        _this.addData.content = content;
        _this.other_add();

        sessionStorage.removeItem('wish_data');
      }
      // 收藏夹跳转过来的
      var collection_list_str = sessionStorage.getItem('collection_list');
      if (collection_list_str && collection_list_str != '') {
        var collection_list_obj = Util.toJson(collection_list_str);
        var id = collection_list_obj.id || '';
        var type = collection_list_obj.type || '';
        sessionStorage.removeItem('collection_list');
      }

      _this.setDatePickerValue();

    },
    mounted () {
      this.getData();
    },
    methods: {
      // 查看用户详情
      searchUserInfo: function (id) {
        var _this = this;
        _this.userInfo_id = id;
      },
      userInfoBackFun: function (id) {
        var _this = this;
        _this.userInfo_id = id;
      },
      setDatePickerValue: function () {
        var _this = this;
        var DatePickerValue = '';
        var end = new Date();
        var Hours = end.getHours();
        var endyear = Utils.fix(end.getFullYear(), 4);
        var endmonth = Utils.fix(parseInt(end.getMonth() + 1), 2);
        var endday = Utils.fix(end.getDate(), 2);

        if (Hours < 8) {
          DatePickerValue = endyear + '-' + endmonth + '-' + endday + ' ' + '10' + ':' + '00' + ':' + '00';
        } else if (Hours >= 8 && Hours < 19) {
          var endhours = Utils.fix(end.getHours() + 2, 2);
          DatePickerValue = endyear + '-' + endmonth + '-' + endday + ' ' + endhours + ':' + '00' + ':' + '00';
        } else if (Hours >= 19) {
          //明天的时间
          var day3 = new Date();
          day3.setTime(day3.getTime() + 24 * 60 * 60 * 1000);
          var endyear3 = Utils.fix(day3.getFullYear(), 4);
          var endmonth3 = Utils.fix(parseInt(day3.getMonth() + 1), 2);
          var endday3 = Utils.fix(day3.getDate(), 2);
          DatePickerValue = endyear3 + '-' + endmonth3 + '-' + endday3 + ' ' + '10' + ':' + '00' + ':' + '00';
        }
        _this.addData.DatePickerValue = DatePickerValue;
      },
      onChangeTypeSelect: function (val) {
        var _this = this;
        _this.typeSelectid = val;
        _this.page = 1;
        _this.getData();
      },
      // 搜索
      searchFun: function () {
        var _this = this;
        var searchDatePicker = _this.searchDatePicker;
        var from = searchDatePicker[0] || '';
        var to = searchDatePicker[1] || '';
        if (from != '') {
          from = Utils.dateToDate(from);
        }
        if (to != '') {
          to = Utils.dateToDate(to);
        }
        _this.from = from;
        _this.to = to;

        _this.page = 1;
        _this.getData();
      },
      // 排序
      onSortChange: function (data) {
        var _this = this;
        var column = data.column;
        var key = data.key;
        switch (key) {
          case 'title' :
            key = 'title';
            break;
          case 'charge' :
            key = 'u.name';
            break;
          case 'priority' :
            key = 'priority';
            break;
          case 'status' :
            key = 'status';
            break;
          case 'deadline' :
            key = 'deadline';
            break;
        }
        var order = data.order;
        if (order == 'asc' || order == 'desc') {
          _this.sort = key;
          _this.order = order;
          _this.getData();
        } else {
          _this.sort = '';
          _this.order = '';
          _this.getData();
        }
      },
      getData () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          page: _this.page,
          size: _this.size,
          mode: 'single',
          type: _this.typeSelectid,
          sort: _this.sort,
          order: _this.order,
          from: _this.from,
          to: _this.to,
        };
        var params = {
          url: '/task/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.permissions = res.permissions;
            _this.data = _data;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      handleSearch () {
        var _this = this;
        _this.page = 1;
        var searchConName = _this.searchConName;
      },
      changePage (page) {
        var _this = this;
        console.log('page', page);
        _this.page = page;
        _this.getData();
      },
      onRowData: function (data, index) {
        var _this = this;
        _this.show(data.id);
      },
      show: function (id) {
        var _this = this;
        var id = id;
        _this.id = id;

        var data = {
          id: _this.id,
        };
        var params = {
          url: '/task/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var priority = _data.priority;
            var status = _data.status;
            _this.status = status;
            switch (priority) {
              case "normal" :
                priority = '普通';
                break;
              case "important" :
                priority = '重要';
                break;
              case "fatal" :
                priority = '紧急';
                break;
              default:
                break;
            }
            switch (status) {
              case "not-begun" :
                status = '未开始';
                break;
              case "started" :
                status = '已开始';
                break;
              case "paused" :
                status = '已暂停';
                break;
              case "delayed" :
                status = '已延期';
                break;
              case "finished" :
                status = '已完成';
                break;
              case "archived" :
                status = '已归档';
                break;
              case "ahead-finished" :
                status = '提前完成了';
                break;
              case "overtime-finished" :
                status = '延期完成了';
                break;
              default:
                break;
            }
            var cowork_users_arr = [];
            var cowork = _data.cowork;
            for (var k in cowork) {
              if (!cowork[k]) {
                continue;
              }
              var name = cowork[k].name;
              cowork_users_arr.push(name);
            }
            _data.cowork_users = cowork_users_arr.join(' ， ');
            _data.priority = priority;
            _data.status = status;
            _this.dataDetail = _data;
            _this.showCurrentTableData = true;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 隐藏详情页面
      hideDetailModal: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      // 富文本
      initCkeditor () {
        var _this = this;
        Ckeditor.initCkeditor(_this, 'content', function (editor) {
          _this.editor = editor;
          _this.editor.setData(_this.addData.content);
        });
      },
      // 获取选人 树信息
      getTreeData: function () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          id: 1
        };
        var params = {
          url: '/department/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data || [];
            var TreeData = [];
            TreeData.push(data);
            var chargeTreeData = Utils.cloneObj(TreeData);
            var reportTreeData = Utils.cloneObj(TreeData);
            _this.toDataFun(TreeData);
            _this.toDataFuncharge(chargeTreeData);
            _this.toDataFunreport(reportTreeData);
            _this.TreeData = TreeData;
            _this.chargeTreeData = Utils.cloneObj(chargeTreeData);
            _this.reportTreeData = Utils.cloneObj(reportTreeData);
          } else {
            _this.$Message.error('查询人员信息失败!');
          }
        }
      },
      // 负责人 处理树信息
      toDataFuncharge: function (arr) {
        var _this = this;
        arr.forEach(function (e) {
          e.title = e.name;
          e.expand = true;//展开
          if (e.type) {
            e.type = 'dep';
          } else {
            e.type = 'user';
            if (e.id == _this.addData.chargeId) {
              e.selected = true;// 选中
            }
          }
          var staff = e.staff || [];
          var children = e.children || [];
          if (children.length == 0) {
            e.children = [];
          }
          e.children.push(...staff);
          _this.toDataFuncharge(e.children);
        });
      },
      // 协作人 处理树信息
      toDataFun: function (arr) {
        var _this = this;
        arr.forEach(function (e) {
          e.title = e.name;
          e.expand = true;//展开
          if (e.type) {
            e.type = 'dep';
            var checked_dep_arr = _this.checked_dep_arr;
            if (Utils.idInArray(e.id, checked_dep_arr)) {
              e.checked = true;// 选中
            }
          } else {
            e.type = 'user';
            var checked_users_arr = _this.checked_users_arr;
            if (Utils.idInArray(e.id, checked_users_arr)) {
              e.checked = true;// 选中
            }
          }
          var staff = e.staff || [];
          var children = e.children || [];
          if (children.length == 0) {
            e.children = [];
          }
          e.children.push(...staff);
          _this.toDataFun(e.children);
        });
      },
      // 知会人 处理树信息
      toDataFunreport: function (arr) {
        var _this = this;
        arr.forEach(function (e) {
          e.title = e.name;
          e.expand = true;//展开
          if (e.type) {
            e.type = 'dep';
          } else {
            e.type = 'user';
            var checked_users_arr = _this.report_checked_users_arr;
            if (Utils.idInArray(e.id, checked_users_arr)) {
              e.checked = true;// 选中
            }
          }
          var staff = e.staff || [];
          var children = e.children || [];
          if (children.length == 0) {
            e.children = [];
          }
          e.children.push(...staff);
          _this.toDataFunreport(e.children);
        });
      },
      // 选中负责人
      onSelectChange: function (item) {
        var _this = this;
        if (item.length > 0 && item[0].type == 'user') {
          _this.addData.chargeId = item[0].id;
        } else {
          _this.addData.chargeId = '';
          _this.$Message.error('请选择一个负责人!');
        }
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 设置默认上报人
      reportUserFun: function () {
        var _this = this;
        _this.getreportUser();
        _this.reportUser = true;
      },
      // 查询已设置的列表
      getreportUser () {
        var _this = this;
        _this.report_checked_users_arr = [];
        var data = {};
        var params = {
          url: '/noticer/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.report_checked_users_arr = _data;
          } else {
            _this.$Message.error('查询上报人失败!');
          }
          _this.getTreeData();
        }
      },
      // 默认上报人
      hidereportUser: function () {
        var _this = this;
        _this.reportUser = false;
      },
      // 保存默认上报人
      savereportUser: function () {
        var _this = this;
        var CheckedNodes = _this.$refs.report_user.getCheckedNodes();
        var departments = [];
        var users = [];
        for (var k in CheckedNodes) {
          if (!CheckedNodes[k]) {
            continue;
          }
          var id = CheckedNodes[k].id;
          var type = CheckedNodes[k].type;
          if (type == 'dep') {
          } else if (type == 'user') {
            users.push(id);
          }
        }
        var data = {
          report_users: users
        };
        var params = {
          url: '/noticer/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.hidereportUser();
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 隐藏编辑页面
      hideAddModal: function () {
        var _this = this;
        _this.saveLoading = false;
        _this.addCurrentTableData = false;
        _this.task_type = '';
        _this.task_type_id = '';
        _this.addData.title = '';
        _this.addData.content = '';
        _this.addData.DatePickerValue = '';
        _this.addData.priority = '';
        _this.addData.chargeId = '';
        if (_this.children == 'children') {
          _this.show(_this.pid);
        }
      },
      // 其他功能转任务，跳转到添加界面
      other_add: function () {
        var _this = this;
        _this.saveLoading = false;
        _this.addData.DatePickerValue = '';
        _this.addData.priority = '';
        _this.addData.chargeId = '';
        _this.TreeData = [];
        _this.chargeTreeData = [];
        _this.checked_users_arr = [];
        _this.report_checked_users_arr = [];
        _this.getreportUser();
        _this.setDatePickerValue();
        _this.ajaxType = 'add';
        _this.children = '';
        _this.pid = 0;
        _this.addCurrentTableData = true;
      },
      // 显示添加界面
      add: function () {
        var _this = this;
        _this.saveLoading = false;
        _this.addData.title = '';
        _this.addData.content = '';
        _this.addData.DatePickerValue = '';
        _this.addData.priority = '';
        _this.addData.chargeId = '';
        _this.TreeData = [];
        _this.chargeTreeData = [];
        _this.checked_users_arr = [];
        _this.report_checked_users_arr = [];
        _this.task_type = '';
        _this.task_type_id = '';
        _this.getreportUser();
        _this.setDatePickerValue();
        _this.ajaxType = 'add';
        _this.children = '';
        _this.pid = 0;
        _this.addCurrentTableData = true;
      },
      // 添加子任务
      addChildren: function (children) {
        var _this = this;
        _this.saveLoading = false;
        _this.addData.title = '';
        _this.addData.content = '';
        _this.addData.DatePickerValue = '';
        _this.addData.priority = '';
        _this.addData.chargeId = '';
        _this.TreeData = [];
        _this.chargeTreeData = [];
        _this.checked_users_arr = [];
        _this.report_checked_users_arr = [];
        _this.task_type = '';
        _this.task_type_id = '';
        _this.getreportUser();
        _this.ajaxType = 'add';
        _this.pid = _this.id;
        _this.children = children ? children : '';//是否为子任务
        _this.showCurrentTableData = false;
        _this.addCurrentTableData = true;
      },
      // 保存数据
      save: function () {
        var _this = this;
        _this.saveLoading = false;
        var title = _this.addData.title;
        var content = _this.addData.content;
        var priority = _this.addData.priority;
        var DatePickerValue = _this.addData.DatePickerValue;
        var chargeId = _this.addData.chargeId;
        var CheckedNodes = _this.$refs.cowork_tree.getCheckedNodes();
        var report_tree = _this.$refs.report_tree.getCheckedNodes();
        if (!(title && title != '')) {
          _this.$Message.error('请输入标题!');
          return false;
        }
        if (content == '') {
          _this.$Message.error('请输入任务描述!');
          return false;
        }
        if (!(priority && priority != '')) {
          _this.$Message.error('请选择优先级!');
          return false;
        }
        if (!(DatePickerValue && DatePickerValue != '')) {
          _this.$Message.error('请选择交付时间!');
          return false;
        }
        if (!(chargeId && chargeId != '')) {
          _this.$Message.error('请选择一个负责人!');
          return false;
        }
        DatePickerValue = Utils.timestampToFormatDatetime(DatePickerValue);
        var departments = [];
        var users = [];
        var uid = Util.toJson(localStorage.getItem('userInfo')).id;
        for (var k in CheckedNodes) {
          if (!CheckedNodes[k]) {
            continue;
          }
          var id = CheckedNodes[k].id;
          var type = CheckedNodes[k].type;
          if (type == 'dep') {
            departments.push(id);
          } else if (type == 'user' && id != chargeId && id != uid) {
            users.push(id);
          }
        }
        var report_users = [];
        var uid = Util.toJson(localStorage.getItem('userInfo')).id;
        for (var k in report_tree) {
          if (!report_tree[k]) {
            continue;
          }
          var id = report_tree[k].id;
          var type = report_tree[k].type;
          if (type == 'dep') {
          } else if (type == 'user' && id != chargeId && id != uid) {
            report_users.push(id);
          }
        }

        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          pid: _this.pid,
          title: title,
          content: content,
          deadline: DatePickerValue,
          priority: priority,
          charge: chargeId,
          cowork: users,
          noticer: report_users,
          type: _this.task_type,
          type_id: _this.task_type_id,
        };
        var url = '/task/add';
        if (_this.ajaxType == 'update') {
          url = '/task/update';
        }
        if (_this.children == 'addchildren' && _this.ajaxType == 'add') {
          _this.task_pause(_this.pid);// 添加子任务后，原任务变成暂停状态
        }
        var params = {
          url: url,
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.addData.title = '';
            _this.addData.content = '';
            _this.addData.DatePickerValue = '';
            _this.addData.priority = '';
            _this.addData.chargeId = '';

            _this.TreeData = [];
            _this.chargeTreeData = [];
            _this.checked_users_arr = [];
            _this.task_type = '';
            _this.task_type_id = '';

            _this.addCurrentTableData = false;
            if (_this.children == 'children' || _this.children == 'addchildren') {
              _this.show(_this.pid);
            }
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 显示修改界面
      update: function (data, index, children) {
        var _this = this;
        _this.children = children ? children : '';//是否为子任务
        _this.pid = _this.id;
        _this.ajaxType = 'update';
        _this.saveLoading = false;
        var id = data.id;
        _this.id = id;
        var data = {
          id: _this.id,
        };
        var params = {
          url: '/task/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var checked_dep_arr = [];
            var checked_users_arr = [];
            var users = _data.cowork;
            for (var k in users) {
              if (!users[k]) {
                continue;
              }
              checked_users_arr.push(users[k]);
            }
            _this.checked_users_arr = checked_users_arr;
            _this.checked_dep_arr = checked_dep_arr;
            _this.addData.title = _data.title;
            _this.addData.content = _data.content;
            _this.addData.DatePickerValue = _data.deadline;
            _this.addData.priority = _data.priority;
            _this.addData.chargeId = _data.charge.id;
            _this.report_checked_users_arr = _data.noticer || [];

            _this.getTreeData();
            _this.addCurrentTableData = true;
            if (_this.children == 'children') {
              _this.hideDetailModal();
            }
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 完成
      task_over: function (id) {
        var _this = this;
        id = id ? id : _this.id;
        var data = {
          id: id,
          status: 'complate'
        };
        var params = {
          url: '/task/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            _this.showCurrentTableData = false;
          } else {
            _this.$Message.error('提交失败!');
          }
        }
      },
      // 开始
      task_start: function (id) {
        var _this = this;
        id = id ? id : _this.id;
        var data = {
          id: id,
          status: 'start'
        };
        var params = {
          url: '/task/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            _this.showCurrentTableData = false;
          } else {
            _this.$Message.error('提交失败!');
          }
        }
      },
      // 暂停
      task_pause: function (id) {
        var _this = this;
        id = id ? id : _this.id;
        var data = {
          id: id,
          status: 'pause'
        };
        var params = {
          url: '/task/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            _this.showCurrentTableData = false;
          } else {
            _this.$Message.error('提交失败!');
          }
        }
      },
      // 重开
      task_reopen: function (id) {
        var _this = this;
        id = id ? id : _this.id;
        var data = {
          id: id,
          status: 'reopen'
        };
        var params = {
          url: '/task/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            _this.showCurrentTableData = false;
          } else {
            _this.$Message.error('提交失败!');
          }
        }
      },
      // 归档
      task_archive: function (id) {
        var _this = this;
        id = id ? id : _this.id;
        var data = {
          id: id,
          status: 'archive'
        };
        var params = {
          url: '/task/update',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.getData();
            _this.showCurrentTableData = false;
          } else {
            _this.$Message.error('提交失败!');
          }
        }
      },
      // 删除
      remove: function () {
        var _this = this;
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          _this.$Message.error('请填选择要删除的数据!');
          return false;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }
        Modal.confirm(_this, {content: '确定删除选中的信息？'}, function () {
          var data = {
            id: selectionIds,
          };
          var params = {
            url: '/task/deleteMultiple',
            type: Util.method.get,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              _this.page = 1;
              _this.getData();
            } else {
              _this.$Message.error('删除信息失败!');
            }
          }
        }, function () {
        });
      },
      // 导出
      ExportData: function () {
        var _this = this;
        var fields = [
          {
            field: 'id',
            title: '#',
            type: 'int',
            order: 1,
          },
          {
            field: 'title',
            title: '标题',
            type: 'varchar',
            order: 2,
          },
          {
            field: 'creator_name',
            title: '创建人',
            type: 'varchar',
            order: 3,
          },
          {
            field: 'charge_name',
            title: '负责人',
            type: 'varchar',
            order: 4,
          },
          {
            field: 'coworkers',
            title: '协作人',
            type: 'varchar',
            order: 5,
          },
          {
            field: 'priority',
            title: '优先级',
            type: 'varchar',
            order: 6,
          },
          {
            field: 'status',
            title: '状态',
            type: 'varchar',
            order: 7,
          },
          {
            field: 'deadline',
            title: '截止日期',
            type: 'date',
            order: 8,
          },
          {
            field: 'content',
            title: '任务描述',
            type: 'varchar',
            order: 9,
          },
        ];
        var fieldsStr = Util.toStr(fields);
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'task',
          fields: fieldsStr,
        };
        var params = {
          url: '/file/db2excle',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var url = res.data;
            var date = Utils.dateToDateString(new Date());
            Utils.DownloadFile(url, '导出任务_' + date + '.xlsx');
          } else {
            _this.$Message.error('导出信息失败!');
          }
        }
      },
    }
  };
</script>
